<template>
  <el-dialog
    class="gl_dialog_TitleLine"
    width="800px"
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
  >
    <el-form
      ref="api_Post_CompetitiveResultVO"
      :model="api_Post_CompetitiveResultVO"
      :rules="rules"
      class="gl_form_mini"
      label-position="right"
      label-width="140px"
      style="padding-right: 30px;"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item style="float:right;padding-right:70px;">
            <div style="height: 50px" class="gl_mx_10">
              <PersonalImage v-if="resultInfo.registerTypeCodeA == 'I'" :imgurl="resultInfo.imagePathA" :imgheight="'50px'" />
              <img v-else :src="getStaticAvatarUrl(resultInfo.imagePathA)" class="avatar" @error="errorPhoto">
            </div>
            <div>
              <span style="vertical-align: top;">青方：</span>
              <div class="athlete_box">
                <el-popover placement="bottom" width="300" trigger="hover" :content="resultInfo.playerNameA">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.playerNameA ? resultInfo.playerNameA: '- -' }}</div>
                </el-popover>
                <el-popover v-if="resultInfo.registerTypeCodeA != 'T'" style="line-height: 20px;" placement="bottom" width="300" trigger="hover" :content="resultInfo.delegationNameA">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.delegationNameA ? resultInfo.delegationNameA : '- -' }}</div>
                </el-popover>
                <el-popover v-else style="line-height: 20px;" placement="bottom" width="300" trigger="hover" :content="resultInfo.memberNamesA">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.memberNamesA ? resultInfo.memberNamesA : '- -' }}</div>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item style="float:left">
            <div style="position:absolute;top:16px;left:-160px;font-size:20px;font-weight:600">VS</div>
            <div style="height: 50px" class="gl_mx_10">
              <PersonalImage v-if="resultInfo.registerTypeCodeB == 'I'" :imgurl="resultInfo.imagePathB" :imgheight="'50px'" />
              <img v-else :src="getStaticAvatarUrl(resultInfo.imagePathB)" class="avatar" @error="errorPhoto">
            </div>
            <div>
              <span style="vertical-align: top;">红方：</span>
              <div class="athlete_box">
                <el-popover placement="bottom" width="300" trigger="hover" :content="resultInfo.playerNameB">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.playerNameB ? resultInfo.playerNameB: '- -' }}</div>
                </el-popover>
                <el-popover v-if="resultInfo.registerTypeCodeB != 'T'" style="line-height: 20px;" placement="bottom" width="300" trigger="hover" :content="resultInfo.delegationNameB">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.delegationNameB ? resultInfo.delegationNameB : '- -' }}</div>
                </el-popover>
                <el-popover v-else style="line-height: 20px;" placement="bottom" width="300" trigger="hover" :content="resultInfo.memberNamesB">
                  <div slot="reference" class="gl_ellipsis">{{ resultInfo.memberNamesB ? resultInfo.memberNamesB : '- -' }}</div>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="青方得分" prop="combatScoreA">
            <el-input v-model.trim="api_Post_CompetitiveResultVO.combatScoreA" type="text" size="mini" :disabled="isNoEdit" placeholder="请输入青方得分" filterable clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="红方得分" prop="combatScoreB">
            <el-input v-model.trim="api_Post_CompetitiveResultVO.combatScoreB" type="text" size="mini" :disabled="isNoEdit" placeholder="请输入红方得分" filterable clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="胜方" prop="playerWin">
            <el-select v-model="api_Post_CompetitiveResultVO.playerWin" style="width:100%" size="mini" :disabled="isNoEdit" placeholder="请选择胜方" filterable clearable>
              <el-option value="1" label="青方" />
              <el-option value="2" label="红方" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="判定方式" prop="winType">
            <el-select v-model="api_Post_CompetitiveResultVO.winType" style="width:100%" size="mini" :disabled="isNoEdit" placeholder="请选择判定方式" filterable clearable>
              <el-option v-for="item in dict.winType" :key="item.code" :value="item.code" :label="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="比赛状态" prop="statusCode">
            <el-select v-model="api_Post_CompetitiveResultVO.statusCode" style="width:100%" size="mini" placeholder="请选择比赛状态" filterable @change="changeIsNoEdit">
              <template v-for="item in dict.status">
                <template v-if="item.code==='Running' || item.code==='Scheduled' || item.code==='UnOfficial'">
                  <el-option :key="item.code" :value="item.code" :label="item.value" />
                </template>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
      <el-button v-loading="submitComLoading" size="mini" type="primary" @click="submitResult">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import defaultPersonImg from '@/assets/images/face_default.png';
import PersonalImage from '@/components/PersonalImage/index';
import { Api_Post_CompetitiveResultVO } from '@/lib/form/events';
import validator from '@/lib/validate/index.js';
import {
  api_PUT_EventsManagementUnitResultCompetitiveUnitId
} from '@/extend/api/gameswaggerApi/app';
export default {
  components: {
    PersonalImage
  },
  data() {
    return {
      title: '编辑成绩',
      defaultPersonImg: defaultPersonImg,
      dialogVisible: false,
      submitComLoading: false,
      resultInfo: {},
      api_Post_CompetitiveResultVO: new Api_Post_CompetitiveResultVO(),
      rules: {},
      runningRules: {
        combatScoreA: [
          validator.required('红方得分不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkNumber(value, '得分格式错误，必须是整数'));
            },
            trigger: 'blur'
          }
        ],
        combatScoreB: [
          validator.required('青方得分不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkNumber(value, '得分格式错误，必须是整数'));
            },
            trigger: 'blur'
          }
        ],
        statusCode: [validator.required('比赛状态不能为空')]
      },
      unOfficialRules: {
        combatScoreA: [
          validator.required('红方得分不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkNumber(value, '得分格式错误，必须是整数'));
            },
            trigger: 'blur'
          }
        ],
        combatScoreB: [
          validator.required('青方得分不能为空'),
          {
            validator(rule, value, callback) {
              callback(validator.checkNumber(value, '得分格式错误，必须是整数'));
            },
            trigger: 'blur'
          }
        ],
        playerWin: [
          validator.required('获胜方不能为空')
        ],
        winType: [validator.required('获胜方式不能为空')],
        statusCode: [validator.required('比赛状态不能为空')]
      },
      current: {
        unitId: ''
      },
      isNoEdit: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$refs['api_Post_CompetitiveResultVO'].resetFields();
      }
    }
  },
  created() {
    this.getDict();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    open(resultInfo) {
      this.current.unitId = resultInfo.unitId;
      this.resultInfo = resultInfo;
      this.api_Post_CompetitiveResultVO = new Api_Post_CompetitiveResultVO();
      this.api_Post_CompetitiveResultVO.combatScoreA = resultInfo.combatScoreA;
      this.api_Post_CompetitiveResultVO.combatScoreB = resultInfo.combatScoreB;
      if (resultInfo.winnerPosition === 1) {
        this.api_Post_CompetitiveResultVO.playerWin = '1';
        this.api_Post_CompetitiveResultVO.winType = resultInfo.winTypeCode;
      }
      if (resultInfo.winnerPosition === 2) {
        this.api_Post_CompetitiveResultVO.playerWin = '2';
        this.api_Post_CompetitiveResultVO.winType = resultInfo.winTypeCode;
      }
      this.api_Post_CompetitiveResultVO.statusCode = resultInfo.statusCode;
      if (resultInfo.statusCode === 'UnOfficial') {
        this.rules = this.unOfficialRules;
        this.isNoEdit = true;
      } else if (resultInfo.statusCode === 'Running') {
        this.rules = this.runningRules;
        this.isNoEdit = false;
      } else if (resultInfo.statusCode === 'Scheduled') {
        this.rules = {};
        this.isNoEdit = false;
      }
      this.dialogVisible = true;
    },
    changeIsNoEdit(val) {
      this.$refs['api_Post_CompetitiveResultVO'].clearValidate();
      if (val === 'UnOfficial') {
        this.rules = this.unOfficialRules;
        this.isNoEdit = true;
      } else if (val === 'Running') {
        this.rules = this.runningRules;
        this.isNoEdit = false;
      } else if (val === 'Scheduled') {
        this.rules = {};
        this.isNoEdit = false;
      }
    },
    submitResult() {
      this.$refs.api_Post_CompetitiveResultVO.validate(valid => {
        if (!valid) return;
        const playA = {
          id: this.resultInfo.unitResultIdA,
          combatScore: this.api_Post_CompetitiveResultVO.combatScoreA,
          rank: this.api_Post_CompetitiveResultVO.playerWin === '1' ? 1 : 2,
          winTypeCode: this.api_Post_CompetitiveResultVO.playerWin === '1' ? this.api_Post_CompetitiveResultVO.winType : null
        };
        const playB = {
          id: this.resultInfo.unitResultIdB,
          combatScore: this.api_Post_CompetitiveResultVO.combatScoreB,
          rank: this.api_Post_CompetitiveResultVO.playerWin === '2' ? 1 : 2,
          winTypeCode: this.api_Post_CompetitiveResultVO.playerWin === '2' ? this.api_Post_CompetitiveResultVO.winType : null
        };
        this.editCompetitiveResult([playA, playB]);
      });
    },
    // 编辑竞技类比赛成绩
    editCompetitiveResult(resultVO) {
      return new Promise((resolve, reject) => {
        this.submitComLoading = true;
        api_PUT_EventsManagementUnitResultCompetitiveUnitId(this.current.unitId, { statusCode: this.api_Post_CompetitiveResultVO.statusCode }, resultVO).then(res => {
          resolve(res);
          this.submitComLoading = false;
          this.$message({ type: 'success', message: '编辑成绩成功！' });
          this.$emit('refreshPage');
          this.dialogVisible = false;
        }, error => {
          this.submitComLoading = false;
          reject(error);
          this.$message({ type: 'error', message: '编辑成绩失败！' });
        });
      });
    },
    // 头像回显
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultPersonImg;
    }
  }
};
</script>
<style lang="scss" scoped>
.avatar {
  max-width: 50px;
  max-height: 50px;
  vertical-align: middle;
}
.athlete_box {
  display: inline-block;
  vertical-align: bottom;
  width: 100px;
}
</style>
